package org.je.dev.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import org.je.util.StringUtil;

/**
 * @author fanyifeng
 */
public class MessageImage
{
	private BufferedImage	img;
	private Graphics2D		g;
	private Color			back;
	private Color			fontColor;

	public MessageImage(int width, int height) {
		img = new BufferedImage(width,height,FastImageUtil.TEMP_BUFFERED_IMAGE_TYPE);
		g = img.createGraphics();
		this.back = Color.black;
		this.fontColor = Color.white;
	}

	private int stringLength(String msg) {
		return g.getFontMetrics().stringWidth(msg);
	}

	private List<String>	messageList	= new ArrayList<String>();

	public void addString(String str) {
		if (StringUtil.isBlankOrNull(str))
			return;
		messageList.add(str);
	}

	public void setFontColor(Color color) {
		this.fontColor = color;
	}

	public FastImage getFastImage() {
		int maxLen = 0;
		for (String s : messageList) {
			int len = stringLength(s);
			if (len > maxLen) {
				maxLen = len;
			}
		}
		int fontSize = g.getFont().getSize();
		int dh = fontSize + 6;

		int imgH = dh * messageList.size();

		g.setColor(back);
		g.fillRect(0 ,0 ,maxLen ,imgH);
		g.setColor(fontColor);
		for (int i = 0; i < messageList.size(); ++i) {
			g.drawString(messageList.get(i) ,0 ,dh * i + dh - 3);
		}
		messageList.clear();
		return FastImageUtil.toFastImage(img ,maxLen ,imgH);
	}

	/**
	 * @param f
	 */
	public void setFont(Font f) {
		g.setFont(f);
	}

}
